package test;

/**
 * @Author fallrain
 * @Description TODO
 * @Date 2022/2/12 10:46
 * @Version 1.0
 */
public class Singleton01 {

    private static final Singleton01 singleton01 = new Singleton01();


    private Singleton01(){}

    /**
     * 饿汉式 静态常量 可用
     * @return
     */
    public static Singleton01 getSingleton01(){
        return singleton01;
    }

    private static Singleton01 singleton02;

    static {
        singleton02 = new Singleton01();
    }

    /**
     * 饿汉式 静态代码块 可用
     * @return
     */
    public static Singleton01 getSingleton02(){
        return singleton02;
    }

    private static Singleton01 singleton03;

    /**
     * 懒汉式 线程不安全 不可用
     * @return
     */
    public static Singleton01 getSingleton03(){
        if (singleton03 == null){
            singleton03 = new Singleton01();
        }
        return singleton03;
    }

    /**
     * 懒汉式 线程安全 同步方法 不推荐用
     * @return
     */
    public static synchronized Singleton01 getInstance04(){
        if (singleton03 == null){
            singleton03 = new Singleton01();
        }
        return singleton03;
    }

    /**
     * 懒汉式 线程安全 同步代码块 不可用
     * @return
     */
    public static Singleton01 getInstance05(){
        if (singleton03 == null){
            synchronized(Singleton01.class){
                singleton03 = new Singleton01();
            }
        }
        return singleton03;
    }

    /**
     * 懒汉式 双重检查 推荐使用
     * @return
     */
    public static Singleton01 getInstance06(){
        if (singleton03 == null){
            synchronized (Singleton01.class){
                if(singleton03 == null){
                    singleton03 = new Singleton01();
                }
            }
        }
        return singleton03;
    }

    private static class SingletonInstance{
        private static final Singleton01 INSTANCE = new Singleton01();
    }

    /**
     * 静态内部类 推荐使用
     * @return
     */
    public static Singleton01 getInstance07(){
        return SingletonInstance.INSTANCE;
    }
}
